# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql

class XiechengMysqlPipeline(object):
    def __init__(self):
        self.connect = pymysql.connect(
        host =   "localhost",
        db =     "xiecheng",
        user =   "root",
        passwd = "root",
        port=3306,
        charset = 'utf8',
        use_unicode = True
        )
        self.cursor = self.connect.cursor()
    def process_item(self, item, spider):
        self.insert_data(item,table='tourism_info')
        return item
    def insert_data(self,data,table="text"):
        '''
        :param data 要插入的数据
        '''
        keys = ",".join(data.keys())
        values = ",".join(['%s']*len(data))
        sql = 'insert into {table} ({keys}) values ({values})'.format(table=table,keys=keys,values=values)
        try:
            if(self.cursor.execute(sql,tuple(data.values()))):
                self.connect.commit()
        except:
            self.connect.rollback()
      
